#!/usr/bin/node 
const fs = require('fs'),
      http = require('http'),
      qs = require('querystring');


let items = ['eat', 'sleep'];
function genPage() {
  let html = fs.readFileSync('./template.html').toString('utf8');
  let dom=items.map(i=>'<li>'+i+'<>').join('\n');

  html=html.replace('%',dom);

  return html;
}
http.createServer((req,res)=>{
  if(req.url!=='/'){
    res.statusCode=404;
    res.setHeader('Content-Type','textml');
    res.end('<h1>Not Found</h1>');
    return;
                      
  } 
  let data='';
  req.on('data',chunk=>data+=chunk);
  req.on('end',()=>{
    let item=qs.parse(data).item;
    if(item !=='' && typeof item !=='undefined') items.push(item);
                  
    res.writeHead(200,{ 
      'Content-Type':'textml',
      'Content-Length':Buffer.byteLength(genPage())
    });
    res.end(genPage());
                          
  });

}).listen(8080);
